//
//  DemoSettingController.m
//  XBSettingControllerDemo
//
//  Created by XB on 15/9/23.
//  Copyright © 2015年 XB. All rights reserved.
//

#import "SettingController.h"

@interface SettingController ()<UITableViewDataSource,UITableViewDelegate> {
    
    NSMutableArray * dataArray;
}

@property (nonatomic,strong) UITableView  *tablview;
@property (nonatomic,strong) UISwitch *aswitch;

@property (nonatomic,strong)NSArray *itemList;
@end

@implementation SettingController
@synthesize tablview;
@synthesize itemList = _itemList;
- (void)backAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)NavInit{
    
    UIView * view = [[UIView alloc]initWithFrame:NSRect(0, 0, SCREEN_WIDTH, 64)];
    view.backgroundColor  = Maincolors;
    [self.view addSubview:view];
    
    [theAppDelegate settitle:self.view title:@"设置"];
    
    UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backbtn setFrame:CGRectMake(7, 28, 60/2, 50/2)];
    [backbtn setImage:[UIImage imageNamed:@"night_icon_back.png"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backbtn];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
//    dataArray = [NSMutableArray arrayWithObjects:@"推送设置",@"清空缓存",@"给我评分",@"版权声明",@"关于", nil];
    //[NSString stringWithFormat:@"推送设置"],
    self.itemList = @[@[@"清空缓存"],@[@"给我评分",@"版权声明",@"关于"]];
    
    self.view.backgroundColor = WithRed(234, 234, 234, 1);
    self.tablview = [[UITableView alloc]initWithFrame:NSRect(0, 44, SCREEN_WIDTH, SCREEN_HEIGHT-44) style:UITableViewStylePlain];
    self.tablview.backgroundColor = WithRed(239.0, 239.0, 243.0, 1.0);;
    self.tablview.delegate  =self;
    self.tablview.dataSource = self;
    [self.view addSubview:self.tablview];
    [theAppDelegate setExtraCellLineHidden:self.tablview];
    
    [self NavInit];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.itemList objectAtIndex:section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.itemList count];
}


//制定个性标题，这里通过UIview来设计标题，功能上丰富，变化多。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    return view;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10.0f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CELL = @"CELLID";
    
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CELL];
    if(cell == nil){
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CELL];
        
        if(indexPath.section == 0){
            if( indexPath.row == 0){
                
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%0.2fM",[self folderSizeAtPath:[self CachePaths]]];
            }
        }else{
            
            cell.accessoryType = YES;
        }
    }
    
    cell.textLabel.text  = [[self.itemList objectAtIndex:[indexPath section]] objectAtIndex:[indexPath row]];
    cell.textLabel.font = Font(usersize);
    cell.detailTextLabel.font = Font(15);
    cell.backgroundColor  =[UIColor whiteColor];
    
    if(indexPath.section == 1 && indexPath.row == 1){
        
        cell.separatorInset = UIEdgeInsetsMake(0, SCREEN_WIDTH, 0, 0);
        
    }
    cell.separatorInset = UIEdgeInsetsMake(0, 16, 0, 20);
    
    return cell;
}


- (UISwitch *)aswitch
{
    if (!_aswitch) {
        _aswitch = [[UISwitch alloc]init];
        
        CGRect frame = _aswitch.frame;
        frame.origin.x = SCREEN_WIDTH - frame.size.width - XBIndicatorToRightGap;
        frame.origin.y = 5;
        _aswitch.frame = frame;
        [_aswitch addTarget:self action:@selector(switchTouched:) forControlEvents:UIControlEventValueChanged];
    }
    return _aswitch;
}
- (void)switchTouched:(UISwitch *)sw
{
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(indexPath.section == 0){
        
        switch (indexPath.row) {
            case 0:{
                
                UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
                
                
                NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:[self CachePaths]];
                DebugLog(@"files :%lu",(unsigned long)[files count]);
                for (NSString *p in files) {
                    NSError *error;
                    NSString *path = [[self CachePaths] stringByAppendingPathComponent:p];
                    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                        [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                    }
                }
                
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%0.2fM",[self folderSizeAtPath:[self CachePaths]]];
                [self.tablview reloadData];
                
            }
                
                break;
            
        }

    }else{
        
        switch (indexPath.row) {
           
            case 0:
                
                break;
            case 1:{

//                aboutViewController * about =[[aboutViewController alloc]init];
//                about.newurl = url_net_Copyright;
//                about.titleLabel = @"版权声明";
//                [self.navigationController pushViewController:about animated:YES];
                
            }

                break;
            case 2:{
                
//                aboutViewController * about =[[aboutViewController alloc]init];
//                about.newurl = url_net_about;
//                about.titleLabel = @"关于";
//                [self.navigationController pushViewController:about animated:YES];
//                
            }
                
                break;
                
            default:
                break;
        }

        
    }
    
    
}

//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

//单个文件的大小
- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


-(NSString*)CachePaths{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachesDir = [paths objectAtIndex:0];
    
    return cachesDir;
}

@end
